/**
 * Production Error Handler (Simplified)
 *
 * 轻量级本地错误处理器，专为MCP工具设计
 * 提供基本的错误分类、日志记录和恢复建议
 * 替代复杂的原企业级错误处理器
 */

const { getLogger } = require('../logging/logger');

class ProductionErrorHandler {
    constructor(configManager) {
        this.configManager = configManager;
        this.logger = getLogger('local-error-handler');
        this.errorCount = 0;
        this.recentErrors = [];
        this.maxRecentErrors = 10; // 只保留最近10个错误
    }

    /**
     * 处理错误的主要方法
     */
    async handleError(error, context = {}) {
        const errorId = this.generateErrorId();
        const timestamp = new Date().toISOString();

        // 分类错误
        const errorInfo = this.categorizeError(error, context);

        // 更新统计
        this.updateStats(errorInfo);

        // 记录错误日志
        this.logError(errorInfo, errorId, timestamp);

        // 存储到最近错误列表
        this.storeRecentError(errorInfo, errorId, timestamp);

        // 返回处理结果
        return {
            errorId,
            handled: true,
            shouldContinue: this.shouldContinueService(errorInfo),
            errorInfo: this.sanitizeError(errorInfo),
            suggestion: this.getRecoverySuggestion(errorInfo)
        };
    }

    /**
     * 简化的错误分类
     */
    categorizeError(error, context) {
        let category = 'unknown';
        let severity = 'medium';
        let isRecoverable = true;

        // 基于错误类型和消息进行分类
        const message = error.message || '';
        const name = error.name || '';

        if (name === 'ConfigurationError' || message.includes('config') || message.includes('settings')) {
            category = 'configuration';
            severity = 'high';
            isRecoverable = false;
        } else if (name === 'ProviderError' || message.includes('API') || message.includes('provider')) {
            category = 'provider';
            severity = message.includes('timeout') ? 'high' : 'medium';
        } else if (name === 'NetworkError' || message.includes('ECONNRESET') || message.includes('ENOTFOUND')) {
            category = 'network';
            severity = 'medium';
        } else if (name === 'ValidationError' || message.includes('validation') || message.includes('invalid')) {
            category = 'validation';
            severity = 'low';
        } else if (name === 'FileSystemError' || message.includes('ENOENT') || message.includes('EACCES')) {
            category = 'filesystem';
            severity = 'high';
            isRecoverable = false;
        } else if (message.includes('memory') || message.includes('heap')) {
            category = 'memory';
            severity = 'high';
            isRecoverable = true;
        } else if (name === 'TypeError' || message.includes('Cannot read property')) {
            category = 'programming';
            severity = 'high';
            isRecoverable = false;
        }

        return {
            category,
            severity,
            isRecoverable,
            message,
            name,
            code: error.code,
            stack: error.stack,
            context,
            timestamp: new Date().toISOString()
        };
    }

    /**
     * 更新错误统计
     */
    updateStats(errorInfo) {
        this.errorCount++;
    }

    /**
     * 记录错误日志
     */
    logError(errorInfo, errorId, timestamp) {
        const logLevel = this.getLogLevel(errorInfo.severity);

        this.logger[logLevel](`Error [${errorId}]: ${errorInfo.category} - ${errorInfo.message}`, {
            category: errorInfo.category,
            severity: errorInfo.severity,
            isRecoverable: errorInfo.isRecoverable,
            context: errorInfo.context,
            stack: errorInfo.stack
        });
    }

    /**
     * 存储最近的错误
     */
    storeRecentError(errorInfo, errorId, timestamp) {
        this.recentErrors.unshift({
            errorId,
            ...errorInfo,
            timestamp
        });

        // 保持最大数量限制
        if (this.recentErrors.length > this.maxRecentErrors) {
            this.recentErrors = this.recentErrors.slice(0, this.maxRecentErrors);
        }
    }

    /**
     * 判断服务是否应该继续
     */
    shouldContinueService(errorInfo) {
        // 不可恢复的错误应该停止服务
        if (!errorInfo.isRecoverable) {
            return false;
        }

        // 编程错误应该停止服务
        if (errorInfo.category === 'programming') {
            return false;
        }

        // 配置错误应该停止服务
        if (errorInfo.category === 'configuration') {
            return false;
        }

        // 其他错误可以继续
        return true;
    }

    /**
     * 清理错误信息（移除敏感信息）
     */
    sanitizeError(errorInfo) {
        return {
            category: errorInfo.category,
            severity: errorInfo.severity,
            message: errorInfo.message,
            name: errorInfo.name,
            code: errorInfo.code,
            isRecoverable: errorInfo.isRecoverable,
            timestamp: errorInfo.timestamp
        };
    }

    /**
     * 获取恢复建议
     */
    getRecoverySuggestion(errorInfo) {
        const suggestions = {
            configuration: '请检查配置文件是否正确设置，或重新配置应用',
            provider: 'AI服务暂时不可用，请稍后重试或检查网络连接',
            network: '网络连接问题，请检查网络状态后重试',
            validation: '输入数据格式不正确，请检查输入内容',
            filesystem: '文件系统权限或路径问题，请检查文件访问权限',
            memory: '内存不足，请关闭其他应用后重试',
            programming: '代码逻辑错误，请检查实现或联系开发者',
            unknown: '未知错误，请查看日志获取更多信息'
        };

        return suggestions[errorInfo.category] || suggestions.unknown;
    }

    /**
     * 生成错误ID
     */
    generateErrorId() {
        return `err_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`;
    }

    /**
     * 根据严重性获取日志级别
     */
    getLogLevel(severity) {
        switch (severity) {
            case 'low':
                return 'info';
            case 'medium':
                return 'warn';
            case 'high':
                return 'error';
            default:
                return 'error';
        }
    }

    /**
     * 获取错误统计信息
     */
    getStats() {
        return {
            totalErrors: this.errorCount,
            recentErrors: this.recentErrors.length,
            recentErrorDetails: this.recentErrors.slice(0, 5) // 最近5个错误的详细信息
        };
    }

    /**
     * 清除错误历史
     */
    clearHistory() {
        this.recentErrors = [];
        this.errorCount = 0;
        this.logger.info('Error history cleared');
    }
}

module.exports = ProductionErrorHandler;